import os
import fitz
from tqdm import *
import cv2

IMAGE_DPI = 300
PDF_DPI = 72
K = 0.15 #缩放系数

def pdf_to_images(pdf_path):
    doc = fitz.open(pdf_path)
    try:
        # 循环处理每一个page
        for page_number in trange(len(doc)):
            page = doc[page_number]

            # 确定输出路径
            output_image_path = f"{pdf_path}-{page_number}.png" 
            #print(f"    {page_number+1}/{len(doc)}")
            page_to_image(page,output_image_path) 

    finally:
        doc.close()    


def page_to_image(page,output_image_path):
    zoom_x = IMAGE_DPI/PDF_DPI*K #水平分辨率缩放系数
    zoom_y = IMAGE_DPI/PDF_DPI*K #垂直分辨率缩放系数
    pix = page.get_pixmap(matrix=fitz.Matrix(zoom_x,zoom_y)) #添加值
    pix.save(output_image_path)
    binary_image(output_image_path,output_image_path,230)



def binary_image(input_path, output_path, threshold_value=128):
    """
    对图片进行二值化处理并保存。

    :param input_path: 输入图片的路径
    :param output_path: 输出二值化图片的路径
    :param threshold_value: 全局阈值法的阈值
    """
    # 读取图片
    image = cv2.imread(input_path, cv2.IMREAD_GRAYSCALE)

    _, binary_image = cv2.threshold(image, threshold_value, 255, cv2.THRESH_BINARY)

    # 保存二值化后的图片
    cv2.imwrite(output_path, binary_image)

def main(folder_path):
    file_paths = []
    # 遍历指定文件夹中的所有文件,处理pdf
    for filename in os.listdir(folder_path):
        # 拼接完整的文件路径
        file_path = os.path.join(folder_path, filename)

         # 检查是否是文件
        if not os.path.isfile(file_path):
            continue

        # 检查是否是文件且文件扩展名为 .pdf
        if not filename.lower().endswith('.pdf'):
            continue

        file_paths.append(file_path)

    count = 0
    for file_path in file_paths:
        count += 1
        print(f"{file_path} in processing ({count}/{len(file_paths)})")

        pdf_to_images(file_path)
        


folder_path ="F:/data/pdf"
main(folder_path)